package com.computergames.server.server.session;

import com.computergames.server.util.GameRoomConfigLoader;
import com.computergames.server.util.RedisUtil;
import com.computergames.server.util.SpringUtil;
import io.netty.channel.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class RoomSessionServiceImpl implements RoomSessionService {

    @Autowired
    private RedisUtil redisUtil;
    private KafkaTemplate<String, String> kafkaTemplate;

    @Override
    public Room createRoom(String name, String roomType, List<String> members) {
        //redisUtil = SpringUtil.getBean(RedisUtil.class);
        kafkaTemplate = SpringUtil.getBean(KafkaTemplate.class);
        int maxPlayers = GameRoomConfigLoader.getMaxPlayersForRoomType(roomType);
        Room room = new Room(name, roomType, members, members.size(), maxPlayers);
//        if(members.size()>maxPlayers || redisUtil.hasKey(name)){
//            return null;
//        }
        if(members.size()>maxPlayers){
            return null;
        }
        //roomService.addRoom(room);
        redisUtil.hmset(name, room.getRoomData());
        //kafkaTemplate.send("test", name, room.toString());

        return room;
    }

    @Override
    public Boolean joinMember(String name, String member) {
        redisUtil = SpringUtil.getBean(RedisUtil.class);
        if (!redisUtil.hasKey(name)) {
            return null; // 房间不存在
        }
        // 获取当前成员集合
        Object membersObj = redisUtil.hget(name, "members");
        if (membersObj == null) {
            return null;//房间成员集合为空
        }
        Set<String> currentMembers = (Set<String>) membersObj;

        // 添加新成员
        currentMembers.add(member);
        // 更新Redis中的成员集合
        redisUtil.hset(name, "members", currentMembers);

        // 更新当前玩家数量
        Integer currentPlayers = (Integer) redisUtil.hget(name, "currentPlayers");
        if (currentPlayers != 0) {
            int newCurrentPlayers = currentPlayers + 1;
            redisUtil.hset(name, "currentPlayers", newCurrentPlayers);
        } else {
            // 如果currentPlayers不存在，初始化为1
            redisUtil.hset(name, "currentPlayers", 1);
        }

        // 判断是否满足开始游戏条件
        try {
            int maxPlayers = (Integer) redisUtil.hget(name, "maxPlayers");
            return currentMembers.size() >= maxPlayers;
        } catch (NumberFormatException e) {
            // 处理或记录异常
            log.error("Failed to parse maxPlayers for room {}: {}", name, e.getMessage());
            return null;// 返回null或其他错误处理方式
        }
    }

    @Override
    public Set<String> getMembers(String name) {
        if (!redisUtil.hasKey(name)) {
            log.warn("Room {} does not exist", name);
            return Collections.emptySet();
        }

        Object membersObj = redisUtil.hget(name, "members");
        if (membersObj == null) {
            log.warn("Room {} has no members", name);
            return Collections.emptySet();
        }

        Set<String> currentMembers = (Set<String>) membersObj;
        return Collections.unmodifiableSet(currentMembers);
    }

    @Override
    public List<Channel> getMembersChannel(String name) {
        return getMembers(name).stream()
                .map(member -> SessionFactory.getSession().getChannel(member))
                .filter(Objects::nonNull)
                .collect(Collectors.toList());
    }

    @Override
    public Boolean removeMember(String name, String member) {
        redisUtil = SpringUtil.getBean(RedisUtil.class);
        if (!redisUtil.hasKey(name)) {
            return false; // 房间不存在
        }

        // 获取当前成员集合
        Object membersObj = redisUtil.hget(name, "members");
        if (membersObj == null) {
            return false; // 成员集合为空或不存在
        }
        Set<String> currentMembers = (Set<String>) membersObj;

        // 移除成员
        boolean isRemoved = currentMembers.remove(member);
        if (!isRemoved) {
            // 成员不在集合中，无需处理
            return false;
        }

        // 更新Redis中的成员集合
        redisUtil.hset(name, "members", currentMembers);

        // 更新当前玩家数量
        Integer currentPlayers = (Integer) redisUtil.hget(name, "currentPlayers");
        if (currentPlayers != null) {
            int newCurrentPlayers = currentPlayers - 1;
            redisUtil.hset(name, "currentPlayers", newCurrentPlayers);
        } else {
            return false;
        }

        return true;
    }

    @Override
    public Boolean removeRoom(String name) {
        return null;
    }

    @Override
    public boolean isRoomFull(String name) {
        redisUtil = SpringUtil.getBean(RedisUtil.class);
        if (!redisUtil.hasKey(name)) {
            return false;
        }

        // 获取当前玩家数量
        Object currentPlayersObj = redisUtil.hget(name, "currentPlayers");
        if (currentPlayersObj == null) {
            return false; // 如果currentPlayers不存在，认为房间未满
        }
        int currentPlayers = (Integer) currentPlayersObj;

        // 获取最大玩家数量
        Object maxPlayersObj = redisUtil.hget(name, "maxPlayers");
        if (maxPlayersObj == null) {
            return false; // 如果maxPlayers不存在，认为房间未满
        }
        int maxPlayers = (Integer) maxPlayersObj;

        return currentPlayers >= maxPlayers; // 当前人数大于等于最大人数时，房间满了
    }
}
